import { message } from "antd";
import axios from "axios";
import { getObjectFinalValue } from "@src/tools/commonTool";
import { BaseParam } from "../env_config";
console.log(BaseParam.fetchUrl);

const theBaseUrl = BaseParam.fetchUrl;

axios.defaults.headers.post["Content-Type"] = "application/json";
export function Request(
	method = "get",
	url,
	data = null,
	baseURL = theBaseUrl,
	timeout = 4000,
	headers = {},
	responseType = "json"
) {
	let param = {
		method,
		url,
		data: /get/i.test(method) ? null : data,
		param: /get/i.test(method) ? data : null,
		baseURL,
		timeout,
		headers,
		responseType,
	};
	if (!!sessionStorage.getItem("AuthorizationCode")) {
		param.headers.Authorization = `Bearer ${sessionStorage.getItem(
			"AuthorizationCode"
		)}`;
	}
	return new Promise((resolve, reject) => {
		axios(param)
			.then((res) => {
				let code = getObjectFinalValue(res, "data.code");
				let resType = getObjectFinalValue(res, "data.type");
				if (responseType === "blob" && resType === "application/json") {
					console.warn(`出问题的接口名:${url}`);
					let fr = new FileReader();
					fr.readAsText(res.data);
					fr.onload = () => {
						const { msg } = JSON.parse(fr.result);
						message.warning(msg);
					};
					reject();
				}
				if (
					res.status.toString().trim() === "401" ||
					(!!code && code.toString().trim() === "401")
				) {
					window.location.replace("#/login");
					reject();
				}
				if (
					res.status.toString().trim() !== "200" ||
					(!!code && code.toString().trim() !== "200")
				) {
					console.warn(`出问题的接口名:${url}`);
					message.warning(res.data.msg);
					reject();
				} else {
					resolve(res.data);
				}
			})
			.catch((err) => {
				message.error("网络出现问题，请检查网络连接！");
				console.warn(`出问题的接口名:${url}`);
				reject(err);
			});
	});
}
